package com.artisan.web.action;

import com.alibaba.fastjson.JSON;
import com.artisan.common.enums.OrderStateEnum2;
import com.artisan.common.pojo.ApiRes;
import com.artisan.commonweb.result.ActionResult;
import com.artisan.medium.wx.pojo.AccessToken;
import com.artisan.medium.wx.service.WxOrderService;
import com.artisan.medium.wx.utils.AccessTokenUtils;
import com.artisan.model.Customer;
import com.artisan.model.CustomerScore;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by szw on 2017/6/15.
 */
@Controller
@RequestMapping("wx/order/")
public class WxOrderController {

	private static final Logger logger = LogManager.getLogger(WxOrderController.class);

	@Autowired
	private WxOrderService wxOrderService;

	/**
	 * 查询订单详情信息
	 * @param request
	 * @param response
	 * @param tranId
	 * @return
	 */
	@RequestMapping(value = "qOrderDetail", method = RequestMethod.GET)
	public ModelAndView qOrderDetail(HttpServletRequest request, HttpServletResponse response, Integer tranId) {

		if (tranId == null) {
			return null;
		}
		Map<String, Object> result = wxOrderService.qOrderDetail(tranId);
		return new ModelAndView("/order_detail", result);
		//return new ModelAndView("/index", result);
	}

	/**
	 * 用户评价
	 * @param request
	 * @param response
	 * @param customerScore
	 * @param photoFiles
	 * @param evaluate
	 * @param orderNo
	 */
	@RequestMapping(value = "/evaluate", method = RequestMethod.POST)
	public void evaluate(HttpServletRequest request, HttpServletResponse response, CustomerScore customerScore,
	                     List<MultipartFile> photoFiles, String evaluate, String orderNo) {


	}

	/**
	 * 取消订单
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cancelOrder")
	public Object cancelOrder(HttpServletRequest request, HttpServletResponse response, String orderNo) {

		Map<String, Object> result = new HashMap<>();
		if (StringUtils.isBlank(orderNo)) {
			logger.error("Parameter orderNo is null");
			result.put("Code", ApiRes.ERROR_CODE);
			result.put("Message", "订单取消失败");
			return JSON.toJSONString(result);
		}

		try {

			int i = wxOrderService.cancelOrder(orderNo);
			if (i == 2) {
				result.put("Code", "0001");
				result.put("Message", "您好，距离师傅上门还有不到两个小时了，师傅已经在上门路了，若您此时取消服务，将会扣除30元上门费。");
			} else if (i == 1){
				result.put("Code", ApiRes.SUCCESS_CODE);
				result.put("state", OrderStateEnum2.IN_AUDIT.getcState());
				result.put("stateValue", OrderStateEnum2.IN_AUDIT.getValue());
				result.put("Message", "订单取消成功");
			} else {
				result.put("Code", ApiRes.NO_DATA_CODE);
				result.put("Message", "订单取消失败");
			}
			return JSON.toJSONString(result);
		} catch (Exception e) {
			logger.error("cancel order failed:" + e.getMessage());
			result.put("Code", ApiRes.ERROR_CODE);
			result.put("Message", "订单取消失败");
			return JSON.toJSONString(result);
		}
	}

	/**
	 * 上门服务时间前两小时内取消扣除部分上门费用
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@ResponseBody
	@RequestMapping("cancelOrderAndDeductMoney")
	public Object cancelOrderAndDeductMoney (HttpServletRequest request, HttpServletResponse response, String orderNo) {
		ActionResult actionResult = new ActionResult();
		if (StringUtils.isBlank(orderNo)) {
			logger.error("Parameter orderNo is null");
			actionResult.setCode(300);
			return actionResult;
		}

		try {

			int i = wxOrderService.cancelOrderAndDeductMoney(orderNo);
			if (i == 1){
				actionResult.setCode(200);
				actionResult.setHint("订单取消成功");
				actionResult.setData(OrderStateEnum2.IN_AUDIT.getcState());
			} else {
				actionResult.setCode(300);
				actionResult.setHint("订单取消失败");
			}
			return actionResult;//new ModelAndView("redirect:/qOrders？openId=" + openId);
		} catch (Exception e) {
			logger.error("cancel order failed:" + e.getMessage());
			actionResult.setCode(300);
			return actionResult;
		}
	}

	/**
	 * 取消订单--未付款的订单
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cancelOrderForUnpay")
	public Object cancelOrderForUnpay(HttpServletRequest request, HttpServletResponse response, String orderNo) {

		//Map<String, Object> result = new HashMap<>();
		ActionResult actionResult = new ActionResult();
		if (StringUtils.isBlank(orderNo)) {
			logger.error("Parameter orderNo is null");
			actionResult.setCode(300);
			return actionResult;
		}

		try {

			String openId = wxOrderService.cancelOrderUnpay(orderNo);
			if (openId == null) {
				actionResult.setCode(300);
				return actionResult;
			}
			actionResult.setCode(200);
			actionResult.setData(openId);
			return actionResult;//new ModelAndView("redirect:/qOrders？openId=" + openId);
		} catch (Exception e) {
			logger.error("cancel order failed:" + e.getMessage());
			actionResult.setCode(300);
			return actionResult;
		}
	}

	/**
	 * 查询订单列表
	 * @param request
	 * @param response
	 * @param type
	 * @return
	 */
	@RequestMapping(value = "/qOrder")
	public ModelAndView qOrder(HttpServletRequest request, HttpServletResponse response, Integer type) {
		String code = request.getParameter("code");
		logger.info("qOrders.do:  code:[" + code + "]");
		AccessToken at=null;
		if(request.getSession().getAttribute("TOKEN")!=null){
			at=(AccessToken) request.getSession().getAttribute("TOKEN");
		}else{
			at = AccessTokenUtils.getAccessTokenUtil(code);
			request.getSession().setAttribute("TOKEN",at);
		}
		String openid = at.getOpenid();
		Map<String, Object> result = new HashMap<>();
		List<Map<String, Object>> orders = wxOrderService.qOrder(openid, type);
		result.put("datas", orders);

		return new ModelAndView("/order",result);
	}

	/**
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/qOrders")
	public ModelAndView qOrders(HttpServletRequest request, HttpServletResponse response, String openId) {
		if (StringUtils.isBlank(openId)) {
			String code = request.getParameter("code");
			logger.info("qOrders.do:  code:[" + code + "]");
			AccessToken at=null;
			if(request.getSession().getAttribute("TOKEN")!=null){
				at=(AccessToken) request.getSession().getAttribute("TOKEN");
			}else{
				at = AccessTokenUtils.getAccessTokenUtil(code);
				request.getSession().setAttribute("TOKEN",at);
			}
			openId = at.getOpenid();
		}

		//String openid = "o33pewztWub26h3WtX3mbY-xKvjE";//at.getOpenid();
		logger.info("openid:[" + openId + "]");
		Map<String, List<Map<String, Object>>> orders = null;
		if (StringUtils.isNotBlank(openId)) {
			orders = wxOrderService.qOrders(openId);
		}
		return new ModelAndView("/order",orders);
	}

	/**
	 * 删除订单（假删除）
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "delOrder")
	public Object deleteOrder(HttpServletRequest request, HttpServletResponse response, String orderNo) {

		ActionResult actionResult = new ActionResult();
		try {
			wxOrderService.deleteOrder(orderNo);
		} catch (Exception e) {
			logger.error("Delete order failed.", e);
			actionResult.setCode(300);
			return actionResult;
		}

		Customer customer = wxOrderService.qCustomerByOrderNo(orderNo);
		String openId = null;
		if (customer != null) {
			openId = customer.getOpenId();
		}
		actionResult.setCode(200);
		actionResult.setData(openId);

		return actionResult;
		//return new ModelAndView("redirect:/wx/order/qOrders.do?openId=" + openId);
	}

	/**
	 * 确认订单
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "confirmOrder")
	public Object confirmOrder(HttpServletRequest request, HttpServletResponse response, String orderNo) {
		ActionResult actionResult = new ActionResult();
		try {
			wxOrderService.confirmOrder(orderNo);
		} catch (Exception e) {
			logger.error("Order confirm failed.", e);
			actionResult.setCode(300);
			return actionResult;
		}

		actionResult.setCode(200);
		actionResult.setData(orderNo);
		return actionResult;
	}

	/**
	 * 用户评价页面
	 * @param request
	 * @param response
	 * @param orderNo
	 * @return
	 */
	@RequestMapping(value = "assessPage")
	public ModelAndView initAssessPage (HttpServletRequest request, HttpServletResponse response, String orderNo) {
		Map<String, Object> result = new HashMap<>();

		result = wxOrderService.qAssessLables();
		result.put("orderNo", orderNo);
		return new ModelAndView("/order_assess", result);
	}

	/**
	 * 用户评价
	 * @param request
	 * @param response
	 * @param stars
	 * @param orderNo
	 * @param lableIds
	 * @param message
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "assess", method = RequestMethod.POST)
	public Object assess(HttpServletRequest request, HttpServletResponse response, Integer stars,
								String orderNo, String lableIds, String message) {

		ActionResult actionResult = new ActionResult();
		try {
			wxOrderService.assess(stars, orderNo, lableIds, message);
		} catch (Exception e) {
			logger.error("Assess failed.", e);
			actionResult.setCode(300);
			return actionResult;
		}
		Customer customer = wxOrderService.qCustomerByOrderNo(orderNo);
		String openId = null;
		if (customer != null) {
			openId = customer.getOpenId();
		}
		actionResult.setCode(200);
		actionResult.setData(openId);

		return actionResult;
	}
}
